import React, { useState } from 'react';
import { Form, Input, Upload, Button, Avatar, message, Space } from 'antd';
import { UserOutlined, UploadOutlined } from '@ant-design/icons';
import { Editor_Default_Directory } from '@/globals/document';
import { uploadFile } from '../../../../apis/public/upload';
import { updateUser } from '../../../../apis/public/user'; 

interface ProfileFormValues {
  username: string;
  email: string;
  phone: string;
  bio: string;
  avatar?: string;
}

const ProfileForm: React.FC = () => {
  const [form] = Form.useForm();
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [avatar, setAvatar] = useState<string>();
  const [loading, setLoading] = useState(false);

  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件！');
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB！');
      return Upload.LIST_IGNORE;
    }
    return true; // 验证通过，允许上传
  };

  const customRequest = async (options: any) => {
    try {
      // 本地预览
      const reader = new FileReader();
      reader.readAsDataURL(options.file);
      reader.onload = () => {
        setAvatarUrl(reader.result as string);
      };
      
      // 拼接文件上传参数
      const formData = new FormData();
      formData.append('file', options.file);
      formData.append('fileName', options.file instanceof File ? options.file.name : 'unknown');
      formData.append('uid', options.file?.uid);
      formData.append('directoryId', Editor_Default_Directory.toString());
      const response = await uploadFile(formData);

      if (options.onSuccess) {
        
        let avatarUrl = `/api/starhub/document/download/${response.data.page?.[0].id}`;
        setAvatar(response.data.page?.[0].id);
        setAvatarUrl(avatarUrl);
        options.onSuccess(response);
      }
      //文件内容提取
      //onUploadSuccess(file); // 调用上传成功回调函数
    } catch (error) {
      if (options.onError) {
        options.onError(error instanceof Error ? error : new Error('上传失败'));
      }
    }
  };

  // 提交处理
  const handleSubmit = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      const response = await updateUser({
        username: values.username,
        email: values.email,
        phone: values.phone,
        avatar:avatar,
        bz:values.bz,
      });
      message.success('更新成功');
      // form.resetFields(); // 清空表单
    } catch (error) {
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const onFinish = (values: ProfileFormValues) => {
    message.success('个人信息更新成功！');
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      style={{ maxWidth: 600 }}
    >
      <Form.Item label="头像" name="avatar"  >
        <Space direction="vertical" align="center">
          <Avatar 
            size={100} 
            src={avatarUrl} 
            icon={<UserOutlined />}
          />
            <Upload
              beforeUpload={beforeUpload}
              maxCount={1}
              customRequest={(options) => {customRequest(options)}}
              showUploadList={false}
              onRemove={()=> { }}
              accept=".png, .jpeg, .jpg, .gif, .bmp, .tiff, .svg, .webp, .ico, .psd, .raw, .heic, .heif"
            >
              <Button icon={<UploadOutlined />}>上传头像</Button>
            </Upload>
        </Space>
      </Form.Item>

      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: '请输入用户名！' }]}
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>

      <Form.Item
        label="邮箱"
        name="email"
        rules={[
          { required: true, message: '请输入邮箱！' },
          { type: 'email', message: '请输入有效的邮箱地址！' }
        ]}
      >
        <Input placeholder="请输入邮箱" />
      </Form.Item>

      <Form.Item
        label="手机号"
        name="phone"
        rules={[
          { required: true, message: '请输入手机号！' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号！' }
        ]}
      >
        <Input placeholder="请输入手机号" />
      </Form.Item>

      <Form.Item
        label="个人简介"
        name="bz"
      >
        <Input.TextArea rows={4} placeholder="请输入个人简介" />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          保存修改
        </Button>
      </Form.Item>
    </Form>
  );
};

export default ProfileForm; 